<template>
    <el-dialog :title="title" v-model="visible" width="580px" :close-on-click-modal="false" @close="emits('close')">
        <el-form ref="formRef"
                 :model="form"
                 :label-width="140">
            <el-form-item label="商家名称:" prop="seller_id">
                <el-select v-model="form.seller_id" filterable @change="companyChange" placeholder="请选择商家名称">
                    <el-option v-for="(item,index) in props.companylist" :key="index" :label="item.company_name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="商品名称:" prop="product_name">
                <el-input v-model="form.product_name" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item label="商品默认售价:" prop="price">
                <el-input v-model="form.price" placeholder="请输入售价"></el-input>
            </el-form-item>
            <el-form-item label="支持支付方式是:" prop="payment_types" v-if="form.seller_id">
                <el-checkbox-group v-model="form.payment_types">
                    <template v-for="(item,index) in dict['payment_type_list']">
                        <el-checkbox  v-if="checkList.indexOf(item.value) > -1" :key="index" :label="item.value">{{ item.text }}</el-checkbox>
                    </template>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="商品列表图:" prop="license_image">
              <el-upload v-model:file-list="product_image_list" 
                :action="baseUrl + 'v1/tools/file/upload'"
                list-type="picture-card" 
                accept=".png,.gif,.jpeg,.jpg" 
                :limit="1" 
                :headers="{
                  'x-token': token,
                }" 
                :data="{
                  module: 'product_image',
                }" 
                :with-credentials="true" 
                :on-remove="(res) => {
                  handleImgRemove(res)
                }" 
                :on-success="(res) => {
                  handleImgSuccess(res);
                }">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>

            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="emits('close')">取 消</el-button>
                <el-button type="primary" @click="save(formRef)">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed, nextTick, onMounted} from 'vue'
import { ElMessage } from 'element-plus'

import type { FormInstance, FormRules, CascaderProps } from 'element-plus'

import { Plus, Close } from "@element-plus/icons-vue";

import systemStore from '@/store/modules/system'

import { getCompanyList } from 'services/common'
import { getProductDetail,addProduct,editProduct } from 'services/product'

import cookies from "libs/cookies";

const baseUrl = import.meta.env.GZG_BASE_URL;

const product_image_list = ref<any>([]);

const $systemStore = systemStore()

const emits = defineEmits(['close', 'success'])

const token = cookies.get("token");

const formRef = ref<FormInstance>()

const form = ref({
    id:undefined,
    payment_types:[],
    price:'',
    product_image:'',
    product_name:'',
    seller_id:''
})

const props = defineProps<{
    dialogVisible:boolean,
    id?:number,
    state:string,
    companylist?:any[]
}>();

const checkList = ref(<any>[])

const visible = ref(false)

const getDetail = (id:any) => {
    getProductDetail({
        id
    }).then(res => {
        form.value = res
        product_image_list.value = [{url: res.product_image}]
        props.companylist?.forEach(item => {
            if (item.id == res.seller_id) {
                checkList.value = item.payment_types
            }
        })
    })
}

const companyChange = (val:any) => {
    console.log(val)

    props.companylist?.forEach(item => {
        if (item.id == val) {
            checkList.value = item.payment_types
        }
    })
}

const handleImgSuccess = (data: any) => {
  if (data.code == 0) {
    form.value.product_image  = data.data.file[0].absolute_path;
    console.log(product_image_list.value)
  }
};

const handleImgRemove = (file: any) => {
  form.value.product_image = ''
}

const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            let data = JSON.parse(JSON.stringify(form.value))
           
            if (data.id) {
                editProduct(data).then(res => {
                    ElMessage.success('操作成功')
                    emits('success')
                })
              
                
            } else {
                addProduct(data).then(res => {
                    ElMessage.success('操作成功')
                    emits('success')
                })
            }
           
        } else {
            console.log('error submit', fields)
        }
    }) 
}

watch(() => props.dialogVisible, async (val) => {
    visible.value = val
    console.log(props.state)
    if (visible.value === true) {
        await nextTick()
        if (props.state == 'edit') {
            if (props.id) {
                getDetail(props.id)
            }
        } else {
            formRef.value?.resetFields()
            form.value.id = undefined
            product_image_list.value = []
            form.value.product_image = ''

        }
        
    }
},{
    immediate:true
})

const dict = computed(() => {
    return systemStore().dict
})

const title = computed(() => {
    return props.state == 'add' ? '新增商品' : '编辑商品'
})

</script>